//
//  B_AddAddressVC.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/8/28.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_AddAddressVC.h"
#import "B_ReleaseFooterView.h"
#import "B_ChangeDataTVC.h"
#import "B_LabelTextViewTVC.h"
#import "B_TapButtonTVC.h"
#import "AddressPickerView.h"
#import "B_AddBankModel.h"
#import "B_AddressListModel.h"

@interface B_AddAddressVC ()<UITextViewDelegate, UITextFieldDelegate>
@property (nonatomic, strong) BaseTableView * mainView;

@property (nonatomic, strong) B_ReleaseFooterView * addFooter;

@property (nonatomic, strong) B_AddressListModel * listModel;
@end

@implementation B_AddAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.type == B_AddressTypeNew) {
        [self setTitle:@"添加新地址"];
        B_AddBankModel * model0 = [B_AddBankModel initB_AddBankModelWithTitle:@"收货人    " placeholder:@"请输入收货人" mapword:@"收货人" alert:@"请输入收货人"];
        B_AddBankModel * model1 = [B_AddBankModel initB_AddBankModelWithTitle:@"联系电话" placeholder:@"请输入联系电话" mapword:@"联系电话" alert:@"请输入联系电话"];
        B_AddBankModel * model2 = [B_AddBankModel initB_AddBankModelWithTitle:@"所在区域" placeholder:@"请选择所在区域" mapword:@"所在区域" alert:@"请选择所在区域"];
        B_AddBankModel * model3 = [B_AddBankModel initB_AddBankModelWithTitle:@"详细地址" placeholder:@"请输入详细住址" mapword:@"详细地址" alert:@"请输入详细住址"];
        B_AddBankModel * model4 = [B_AddBankModel initB_AddBankModelWithTitle:@"设为默认地址" placeholder:@"" mapword:@"设为默认地址" alert:@""];
        model4.value_name = @"1";
        self.dataArray = [NSMutableArray arrayWithObjects:model0, model1, model2, model3, model4, nil];
    } else if (self.type == B_AddressTypeEditor) {
        [self setTitle:@"编辑收货地址"];
        [self getData];
        
    }
    self.view = self.mainView;
   
    
}
- (BaseTableView *)mainView {
    if (!_mainView) {
        WeakSelf(weSelf, self);
        _mainView = [[BaseTableView alloc] init];
        [_mainView addSubview:self.addFooter];
        [self.addFooter mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mainView.mas_left);
            make.right.equalTo(self.mainView.mas_right);
            make.bottom.equalTo(self.mainView.mas_bottom);
            make.height.equalTo(@(80));
        }];
        CGFloat bottom = SCREEN_HEIGHT > 800 ? (80 + 24) : 80;
        [_mainView setTableViewFrameWithTop:5 left:0 right:0 bottom:-bottom];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_ChangeDataTVC" bundle:nil] forCellReuseIdentifier:@"B_ChangeDataTVC"];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_LabelTextViewTVC" bundle:nil] forCellReuseIdentifier:@"B_LabelTextViewTVC"];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_TapButtonTVC" bundle:nil] forCellReuseIdentifier:@"B_TapButtonTVC"];
        _mainView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            return weSelf.dataArray.count;
        };
        _mainView.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            B_AddBankModel * model = weSelf.dataArray[indexPath.row];
            if ([model.map_word isEqualToString:@"详细地址"]) {
                return 150;
            }
            return 55;
        };
        _mainView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            B_AddBankModel * model = weSelf.dataArray[indexPath.row];
            if ([model.map_word isEqualToString:@"详细地址"]) {
                B_LabelTextViewTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_LabelTextViewTVC" forIndexPath:indexPath];
                cell.B_keyLabel.text = model.key_title;
                cell.B_textview.placeholder = model.placeholder_name;
                cell.B_textview.text = model.value_name;
                cell.B_textview.delegate = weSelf;
                cell.B_textview.tag = indexPath.row;
                return cell;
            } else if ([model.map_word isEqualToString:@"所在区域"]) {
                B_TapButtonTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_TapButtonTVC" forIndexPath:indexPath];
                cell.B_valueLabel.hidden = NO;
                cell.B_keyLabel.text = model.key_title;
                
                cell.B_imageView.image = [UIImage imageNamed:@"B_personalcenter_order_arrowbig"];
                if (model.value_name == nil) {
                    cell.B_valueLabel.textColor = [UIColor color_text_deep_gray];
                    cell.B_valueLabel.text = model.placeholder_name;
                    cell.B_valueLabel.textAlignment = NSTextAlignmentRight;
                } else {
                    cell.B_valueLabel.textColor = [UIColor color_text_white];
                    cell.B_valueLabel.text = model.value_name;
                    cell.B_valueLabel.textAlignment = NSTextAlignmentLeft;
                }
                return cell;
            } else if ([model.map_word isEqualToString:@"设为默认地址"]) {
                B_TapButtonTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_TapButtonTVC" forIndexPath:indexPath];
                cell.B_valueLabel.hidden = YES;
                if ([model.value_name isEqualToString:@"1"]) {
                    cell.B_imageView.image = [UIImage imageNamed:@"B_edit_shipping_address_sel"];
                } else {
                    cell.B_imageView.image = [UIImage imageNamed:@"B_edit_shipping_address_not_sel"];
                }
                cell.B_keyLabel.text = model.key_title;
                return cell;
            }
            B_ChangeDataTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_ChangeDataTVC" forIndexPath:indexPath];
            if ([model.map_word isEqualToString:@"联系电话"]) {
                cell.B_textfield.keyboardType = UIKeyboardTypeNumberPad;
            } else {
                cell.B_textfield.keyboardType = UIKeyboardTypeDefault;
            }
            cell.B_keyLabel.text = model.key_title;
            cell.B_textfield.placeholder = model.placeholder_name;
            cell.B_textfield.text = model.value_name;
            cell.B_textfield.delegate = weSelf;
            cell.B_textfield.tag = indexPath.row;
            return cell;
        };
        ///
        _mainView.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            B_AddBankModel * model = weSelf.dataArray[indexPath.row];
            if ([model.map_word isEqualToString:@"所在区域"]) {
                AddressPickerView * address = [[AddressPickerView alloc] initWithShowQu:YES];
                [address show];
                address.sureMessage = ^(NSString *provice, NSString *city, NSString *area) {
                    model.value_name = [NSString stringWithFormat:@"%@ %@ %@", provice, city, area];
                    [weSelf.mainView.tableView reloadData];
                };
            } else if ([model.map_word isEqualToString:@"设为默认地址"]) {
                if ([model.value_name isEqualToString:@"1"]) {
                    model.value_name = @"2";
                } else {
                    model.value_name = @"1";
                }
            }
            [tableView reloadData];
        };
        
    }
    return _mainView;
}

- (B_ReleaseFooterView *)addFooter {
    if (!_addFooter) {
        WeakSelf(weSelf, self);
        _addFooter = [B_ReleaseFooterView initB_ReleaseFooterView];
        [_addFooter.B_SureButton setTitle:@"保存" forState:UIControlStateNormal];
        _addFooter.sureActionBlock = ^{
            //TODO:保存地址的方法
            
            [weSelf submitData];
            
        };
    }
    return _addFooter;
}

#pragma mark -> delegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    B_AddBankModel * model = self.dataArray[textField.tag];
    model.value_name = textField.text;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
    B_AddBankModel * model = self.dataArray[textView.tag];
    model.value_name = textView.text;
}


- (void) submitData {
    WeakSelf(weSelf, self);
    NSMutableDictionary * dictionary = [NSMutableDictionary dictionary];
    
    for (B_AddBankModel * model in self.dataArray) {
        if (ISNULL(model.value_name)) {
            [UIView xg_toast:model.alert_message];
            return;
        }
        if ([model.map_word isEqualToString:@"收货人"]) {
            [dictionary setObject:model.value_name forKey:@"userName"];
            continue;
        }
        if ([model.map_word isEqualToString:@"联系电话"]) {
            if ([model.value_name isMobileNumber]) {
                [dictionary setObject:model.value_name forKey:@"userPhone"];
            } else {
                [UIView xg_toast:@"请输入有效的手机号码"];
                return;
            }
            continue;
        }
        if ([model.map_word isEqualToString:@"所在区域"]) {
            NSArray * arr = [model.value_name componentsSeparatedByString:@" "];
            [dictionary setObject:arr[0] forKey:@"province"];
            [dictionary setObject:arr[1] forKey:@"city"];
            [dictionary setObject:arr[2] forKey:@"district"];
            continue;
        }
        if ([model.map_word isEqualToString:@"详细地址"]) {
            [dictionary setObject:model.value_name forKey:@"location"];
            continue;
        }
        if ([model.map_word isEqualToString:@"设为默认地址"]) {
            [dictionary setObject:model.value_name forKey:@"isDefault"];
            continue;
        }
    }
    
    
    if (weSelf.type == B_AddressTypeNew) {
        [dictionary setObject:getUserId() forKey:@"userId"];
        [NetworkingManager getNetworkRequestWithUrlString:@"/yearnfor/inter/userAddress/addUserAddress" parameters:dictionary isCache:NO succeed:^(id data) {
            if ([data[@"code"] isEqualToString:@"20005"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"addressGetData" object:nil];
                [weSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [KeyWindow makeToast:data[@"message"]];
            }
        } fail:^(NSError *error) {
            [KeyWindow makeToast:@"服务器异常"];
        }];
    } else {
        [dictionary setObject:weSelf.addressId forKey:@"id"];
        [NetworkingManager getNetworkRequestWithUrlString:@"/yearnfor/inter/userAddress/editUserAddress" parameters:dictionary isCache:NO succeed:^(id data) {
            if ([data[@"code"] isEqualToString:@"20005"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"addressGetData" object:nil];
                [weSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [KeyWindow makeToast:data[@"message"]];
            }
        } fail:^(NSError *error) {
            [KeyWindow makeToast:@"服务器异常"];
        }];
    }
    
    
    
}

- (void) getData {
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/userAddress/selectUserAddressInfo/%@", self.addressId] parameters:nil isCache:NO succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20010"]){
            weSelf.listModel = [B_AddressListModel mj_objectWithKeyValues:data[@"values"]];
            B_AddBankModel * model0 = [B_AddBankModel initB_AddBankModelWithTitle:@"收货人    " placeholder:@"请输入收货人" mapword:@"收货人" alert:@"请输入收货人"];
            B_AddBankModel * model1 = [B_AddBankModel initB_AddBankModelWithTitle:@"联系电话" placeholder:@"请输入联系电话" mapword:@"联系电话" alert:@"请输入联系电话"];
            B_AddBankModel * model2 = [B_AddBankModel initB_AddBankModelWithTitle:@"所在区域" placeholder:@"请选择所在区域" mapword:@"所在区域" alert:@"请选择所在区域"];
            B_AddBankModel * model3 = [B_AddBankModel initB_AddBankModelWithTitle:@"详细地址" placeholder:@"请输入详细住址" mapword:@"详细地址" alert:@"请输入详细住址"];
            B_AddBankModel * model4 = [B_AddBankModel initB_AddBankModelWithTitle:@"设为默认地址" placeholder:@"" mapword:@"设为默认地址" alert:@""];
            model0.value_name = weSelf.listModel.userName;
            model1.value_name = weSelf.listModel.userPhone;
            model2.value_name = [NSString stringWithFormat:@"%@ %@ %@", weSelf.listModel.province, weSelf.listModel.city, weSelf.listModel.district];
            model3.value_name = weSelf.listModel.location;
            model4.value_name = weSelf.listModel.isDefault;
            weSelf.dataArray = [NSMutableArray arrayWithObjects:model0, model1, model2, model3, model4, nil];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
        [weSelf.mainView.tableView reloadData];
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
